<template>
  <div id="login">
    <!--中间的容器盒子-->
    <div class="login_box">
     <h3>社区团购后台管理系统</h3>
      <!--登录表单-->
      <el-form ref="loginFormRef" :rules="loginFormRules" :model="loginForm" label-width="0px"
               class="loginForm_box">
        <el-form-item prop="username">
          <el-input placeholder="请输入账号" v-model="loginForm.username"
                    prefix-icon="el-icon-user" clearable></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input placeholder="请输入密码" v-model="loginForm.password" prefix-icon="el-icon-lock" clearable show-password></el-input>
        </el-form-item>
        <el-form-item >
          <el-button class="btns" type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 表单对应的数据对象
      loginForm: {
        username: '',
        password: ''
      },
      // 表单校验规则
      loginFormRules: {
        username: [
          { required: true, message: '请输入登录账号', trigger: 'blur'},
          { min: 5, max: 8, message: '请正确输入账号', trigger: 'blur'}
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur'},
          { min: 6, max: 10, message: '请正确输入密码', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
   /* // 重置按钮
    resetLoginForm() {
      // 重置表单的所有项
      this.$refs.loginFormRef.resetFields()
    },*/
    // 登录按钮
    login() {
      // 判断表单校验是否有效
      this.$refs.loginFormRef.validate(async valid => {
        if(!valid)
          return this.$message.error('校验失败')

        // 发登录请求
        const {data: res} = await this.$http.post('/backUser/login', this.loginForm)
        console.log(res);
        if(res.meta.status !== 200)
          return this.$message.error('用户名或密码有误!')

        this.$message.success('登录成功')

        // 保存 token 和 res.data到 sessionStorage
        sessionStorage.setItem('token', res.data.token)
        sessionStorage.setItem('data',JSON.stringify(res.data))
        console.log(sessionStorage.getItem('data'))
        // 导航到 Home 组件
        this.$router.push('/home')

      })
    }
  }
};
</script>

<style>
#login {
  background-color: #1e3042;
  height: 100%;
}

.login_box {
  width: 450px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .12);


  /* 绝对居中 */
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  h3 {
    margin: 0;
    text-align: center;
    padding: 20px 0px;
    color: white;
  }
}


.loginForm_box {
 /* position: absolute;
  bottom: 0px;*/
  width: 100%;
  padding: 0 60px;
  /*宽度会包含边框*/
  box-sizing: border-box;
}

.btns {
  width: 100%;
}
</style>